package withdraw

import (
	"context"
	"errors"
	"github.com/xinliangnote/go-gin-api/configs"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func NewModel() *Withdraw {
	return new(Withdraw)
}

func (p *Withdraw) List(db *mongo.Client, pageIndex uint, pageSize uint) ([]Withdraw, error) {
	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("withdraw")
	skip := int64((pageIndex - 1) * pageSize)
	findOptions := options.Find()
	findOptions.SetSort(bson.D{{"_id", -1}})
	findOptions.SetSkip(skip)
	findOptions.SetLimit(int64(pageSize))
	filter := bson.M{}
	if p.ChainName != "" {
		filter["chainName"] = p.ChainName
	}
	find, err := client.Find(context.TODO(), filter, findOptions)
	if err != nil {
		return nil, err
	}
	var withdrawList []Withdraw
	err = find.All(nil, &withdrawList)
	if err != nil {
		return nil, err
	}
	return withdrawList, nil
}

func (p *Withdraw) Count(db *mongo.Client) (count int64, err error) {
	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("withdraw")

	filter := bson.M{}
	if p.ChainName != "" {
		filter["chainName"] = p.ChainName
	}
	count, err = client.CountDocuments(context.TODO(), filter)
	if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
		return 0, err
	}
	return count, nil
}
